<?php

use yii\helpers\ArrayHelper;
use console\db\Migration;
use yii\base\Exception;

/**
 * 创建分表自增主键存储过程
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m190104_091351_p_gen_sequence_id extends Migration {

    /**
     * @inheritdoc
     */
    public function init() {
        parent::init();
        $procedureName = ArrayHelper::getValue(Yii::$app->params, 'sequence.name', $this->procedureName);
        if (!$procedureName) {
            throw new Exception('This procedure name is not exists or empty!');
        }
        $this->procedureName = $procedureName;
    }

    /**
     * @inheritdoc
     */
    public function safeUp() {
        $sql = $this->getData($this->procedureName . '.sql');
        if (empty($sql)) {
            return false;
        }

        /**
         * @procedure `generateSequenceId`.
         */
        $this->procedureBuilder([
            'name' => $this->procedureName,
            'params' => [
                [
                    'name' => 'generatorName',
                    'type' => 'varchar',
                    'size' => 32,
                ],
            ],
            'sql' => $sql
        ]);
    }

    /**
     * @inheritdoc
     */
    public function safeDown() {
        $this->dropProcedure($this->procedureName);
    }

}
